from time import time
import matplotlib.pyplot as plt 
import pandas as pd
from sklearn.model_selection import ( train_test_split)  # , StratifiedKFold, KFold, cross_val_score, GridSearchCV, )
import numpy as np
import os
import json

def timer(func):
    def func_wrapper(*args,**kwargs):
        time_start = time()
        result = func(*args,**kwargs)
        time_end = time()
        time_spend = time_end - time_start
        print(f'{func.__name__} 耗时 {time_spend:.3f} s')
        return result
    return func_wrapper

def plot_line(pred, true, root, name1='pred', name2='true', length=1000):
    plt.figure(figsize=(30, 6))
    plt.plot(pred[:length], alpha=0.5, label=name1)
    plt.plot(true[:length], alpha=0.5, label=name2)
    plt.legend()
    plt.savefig(root)
    plt.close()
   

def sp_sort(root=None):
    if root is None:
        root = 'result/frame/lgb/10/Pos_make_series_thred_month_semple'
    info = pd.DataFrame(columns=['sp'])
    file_list = os.listdir(root)
    for i in file_list:
        file = os.path.join(root,i,'info.csv')
        info_i = pd.read_csv(file, index_col=0)
        info.loc[i] = info_i.loc['sp'].values
    info.sort_values(by='sp',ascending=False)
    info.to_csv(os.path.join(root,'info_all.csv'))
    print('fin')
    

class MyEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, np.integer):
            return int(obj)
        elif isinstance(obj, np.floating):
            return float(obj)
        elif isinstance(obj, np.ndarray):
            return obj.tolist()
        else:
            return super(MyEncoder, self).default(obj)

